package com.yjt.sousou.detail;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;
import com.permissionx.guolindev.PermissionX;
import com.yjt.sousou.Api;
import com.yjt.sousou.Constant;
import com.yjt.sousou.base.BaseCreateOrderActivity;
import com.yjt.sousou.camera.preview.ImagePreviewActivity;
import com.yjt.sousou.create.CreateConst;
import com.yjt.sousou.create.FaultTypeAdapter;
import com.yjt.sousou.create.PicRecycleAdapter;
import com.yjt.sousou.create.entity.FaultType;
import com.yjt.sousou.create.entity.FaultTypeSelect;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.create.entity.ImageItem;
import com.yjt.sousou.create.entity.UpLoadFile;
import com.yjt.sousou.detail.entity.EventUser;
import com.yjt.sousou.detail.entity.FilterBean;
import com.yjt.sousou.detail.entity.Special;
import com.yjt.sousou.detail.entity.UserEntity;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.BitCompressUtil;
import com.yjt.sousou.utils.GetTimeUtil;
import com.yjt.sousou.utils.HDPreference;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.internal.utils.PathUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yjt.sousou.R.color;
import static com.yjt.sousou.R.id;
import static com.yjt.sousou.R.layout;
import static com.yjt.sousou.R.mipmap;
import static com.yjt.sousou.camera.preview.ImagePreviewActivity.CURRENT_POSITION;
import static com.yjt.sousou.camera.preview.ImagePreviewActivity.IMAGE_DATA;


/**
 * 作者：83734
 * 时间：2018/11/27
 * 描述：维修过程
 */
public class ProcessActivity extends BaseCreateOrderActivity {
    @BindView(id.tv_title)
    TextView mTvTitle;
    @BindView(id.rl_pic)
    RecyclerView mRlPic;
    @BindView(id.rl_main)
    RelativeLayout mRlMain;
    @BindView(id.tv_mic)
    TextView mTvMic;
    @BindView(id.tv_info)
    TextView mTvInfo;
    @BindView(id.mic_icon)
    ImageView mMicIcn;
    @BindView(id.time_display)
    Chronometer mChronometer;//录音定时
    @BindView(id.audio_layout)
    RelativeLayout mAudioLayout;
    @BindView(id.scrollview)
    NestedScrollView mScrollView;
    @BindView(id.iv_play_audio)
    ImageView mIvPlayAudio;
    @BindView(id.tv_fix_ok)
    TextView mTvFixOk;
    @BindView(id.tv_fix_no)
    TextView mTvFixNo;
    @BindView(id.tv_receive_time)
    TextView mTvReceiveTime;
    @BindView(id.tv_finish_time)
    TextView mTvFinishTime;
    @BindView(id.tv_special)
    TextView mTvSpecial;
    @BindView(id.rv_fault_type)
    RecyclerView mRvFaultType;
    @BindView(id.et_cause)
    EditText mEtCause;
    @BindView(id.et_special_des)
    EditText mEtSpecialDes;
    @BindView(id.rl_users)
    RecyclerView mRlUsers;
    @BindView(id.tv_add_person_title)
    TextView mTvAddPersonTitle;
    @BindView(id.tv_add_person)
    TextView mTvAddPerson;
    private int fixState = 2;
    private List<FaultTypeSelect> mFaultTypes = new ArrayList<>();
    private FaultTypeAdapter mFaultTypeAdapter;
    private List<FaultType.DataBean> mFaultTypeLeft = new ArrayList<>();
    private List<FaultType.DataBean.GzlxListsBean> mFaultTypeRight = new ArrayList<>();
    private String faultLeftId = "";
    private String faultRightId = "";
    private String faultName = "";
    private String faultNameRight = "";
    private String receiveTimeStamp = "";
    private String finishTimeStamp = "";
    private boolean isReceiveTime = false;
    private String fileIds = "";
    private String orderId = "";
    private List<FilterBean> mSpecials = new ArrayList<>();
    private String specialId = "";
    private List<TextView> mTextView = new ArrayList<>();
    private String continueState = "";
    //维修员ids
    private String weixiuyuanIds = "";
    private String weixiuyuanName = "";
    private BaseQuickAdapter<UserEntity.DataBean,BaseViewHolder> mUserAdapter;

    @Override
    protected Object setContentLayout() {
        return layout.activity_process;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        mTvTitle.setText("维修过程");
        mTextView.add(mTvFixOk);
        mTextView.add(mTvFixNo);
        orderId = getIntent().getStringExtra("orderId");
        String repairState = getIntent().getStringExtra("repairState");
        setState(mTextView, repairState.equals("已修好") ? 0 : 1);
        String receiveTime = getIntent().getStringExtra("receiveTime");
        weixiuyuanName = getIntent().getStringExtra("weixiuyuan");
        weixiuyuanIds = getIntent().getStringExtra("weixiuyuanids");
        mUserId = HDPreference.getUserId(LoginTag.USER_ID.name());
        String permission =  HDPreference.getUserId(LoginTag.PERMISSION.name());
        if(!permission.contains("121")&&!permission.contains("125")){
            mTvAddPersonTitle.setVisibility(View.GONE);
            mTvAddPerson.setVisibility(View.GONE);
        }
        ArrayList<FaultTypeSelect> faulttypes = getIntent().getParcelableArrayListExtra("faulttypes");
        if (faulttypes != null && faulttypes.size() > 0) {
            mFaultTypes.addAll(faulttypes);
        }
        if (!TextUtils.isEmpty(receiveTime)) {
            try {
                receiveTimeStamp = GetTimeUtil.ymdhm2Timestamp4(receiveTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        finishTimeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        initRecycleView();
        mTvReceiveTime.setText(receiveTime);
        mTvFinishTime.setText(GetTimeUtil.getYMDHM(System.currentTimeMillis()));
        mUserId = HDPreference.getUserId(LoginTag.USER_ID.name());
        initAudio();
        PermissionX.init(this)
                .permissions(Manifest.permission.RECORD_AUDIO,Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> ToastUtils.showLong("即将申请的权限是程序必须依赖的权限"))
                .onForwardToSettings((scope, deniedList) -> ToastUtils.showLong("您需要去应用程序设置当中手动开启权限"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                    } else {
                        ToastUtils.showLong("录音权限被禁止，无法录音");
                    }
                });
        initData();
        mTvMic.setOnTouchListener(touchListener);
        mChronometer.setOnChronometerTickListener(tickListener);
        initUserRecyclerView();
    }

    private List<UserEntity.DataBean> getOriginList(){
        List<UserEntity.DataBean> list = new ArrayList<>();
        String[] names = weixiuyuanName.split(",");
        String[] ids = weixiuyuanIds.split(",");
        for (int i = 0; i < names.length; i++) {
            UserEntity.DataBean dataBean = new UserEntity.DataBean();
            dataBean.setId(ids[i]);
            dataBean.setUsername(names[i]);
            dataBean.setSelected(true);
            list.add(dataBean);
        }
        return list;
    }

    private void initUserRecyclerView() {
        //设置显示维修员列表的recyclerview  使用流式布局显示
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        mRlUsers.setLayoutManager(layoutManager);

        mUserAdapter = new BaseQuickAdapter<UserEntity.DataBean,BaseViewHolder>(layout.item_flex_box,getOriginList()) {
            @Override
            protected void convert(BaseViewHolder helper, UserEntity.DataBean item) {
                helper.setText(id.tv_name,item.getUsername());
                helper.getView(id.iv_delete).setOnClickListener(v -> {
                    mUserAdapter.getData().remove(helper.getAdapterPosition());
                    notifyDataSetChanged();
                    setUserIds();
                    LogUtils.i(weixiuyuanIds);
                });
            }
        };
        mRlUsers.setAdapter(mUserAdapter);
    }

    private void setUserIds() {
        StringBuilder sb = new StringBuilder("");
        for (UserEntity.DataBean bean : mUserAdapter.getData()) {
            if(bean.isSelected()){
                sb.append(bean.getId()).append(",");
            }
        }
        if(!sb.toString().equals("")){
            weixiuyuanIds =  sb.toString().substring(0,sb.toString().length()-1);
        }else {
            weixiuyuanIds = "";
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initData() {
        OkGo.<FaultType>get(Api.get().getFaultType())
                .tag(this)
                .execute(new DialogCallback<FaultType>(FaultType.class, this) {
                    @Override
                    public void onSuccess(Response<FaultType> response) {
                        FaultType faultType = response.body();
                        if (faultType != null && faultType.getData().size() != 0) {
                            mFaultTypeLeft.addAll(faultType.getData());
                        }
                    }
                });
        OkGo.<Special>get(Api.get().getClooectionList())
                .tag(this)
                .execute(new DialogCallback<Special>(Special.class, this) {
                    @Override
                    public void onSuccess(Response<Special> response) {
                        Special special = response.body();
                        if (special != null && special.getReturncode().equals("0") && special.getData().size() != 0) {
                            mSpecials.add(new FilterBean("", "正常工单"));
                            for (Special.DataBean data : special.getData()) {
                                mSpecials.add(new FilterBean(data.getId(), data.getCollection()));
                            }
                        }
                    }
                });
    }

    /**
     * 获取选择维修员的列表
     */
    @Subscribe
    public void getPerson(EventUser eventUser) {
        if (eventUser != null) {
            weixiuyuanIds = eventUser.getUserIds();
            mUserAdapter.setNewData(eventUser.getUsers());
            LogUtils.i(weixiuyuanIds);
        }
    }

    private void submitOrder() {
        if (!TextUtils.isEmpty(mAudioPath) || mImgData.size() > 1) {
            uploadFile();
        } else {
            submit();
        }
    }

    @OnClick({id.iv_play_audio, id.tv_fix_ok, id.tv_fix_no, id.tv_submit, id.tv_fault_type, id.tv_receive_time,
            id.tv_finish_time, id.tv_special, id.tv_add_person})
    void onClick(View view) {
        switch (view.getId()) {
            case id.iv_play_audio:
                AnimationDrawable animationDrawable = (AnimationDrawable) mIvPlayAudio.getDrawable();
                animationDrawable.start();
                playAudio();
                break;
            case id.tv_fix_ok:
                fixState = 1;
                setState(mTextView, 0);
                break;
            case id.tv_fix_no:
                fixState = 2;
                setState(mTextView, 1);
                break;
            case id.tv_submit:
                if (TextUtils.isEmpty(receiveTimeStamp) || TextUtils.isEmpty(finishTimeStamp)) {
                    showToast("请填写时间");
                    return;
                }
                if (Long.parseLong(receiveTimeStamp) > Long.parseLong(finishTimeStamp)) {
                    showToast("接单时间不能晚于完成时间");
                }
                if (!TextUtils.isEmpty(specialId)) {
                    showBackStatePop();
                    makeWindowDark();
                } else {
                    submitOrder();
                }
                break;
            case id.tv_fault_type:
                showFaultTypePop();
                makeWindowDark();
                break;
            case id.tv_receive_time:
                isReceiveTime = true;
                showTime(mRlMain);
                makeWindowDark();
                break;
            case id.tv_finish_time:
                isReceiveTime = false;
                showTime(mRlMain);
                makeWindowDark();
                break;
            case id.tv_special:
                CommonPop departmentPop = new CommonPop(this, mSpecials, new CommonPop.ResultListener() {
                    @Override
                    public void res(String id, String name) {
                        specialId = id;
                        mTvSpecial.setText(name);
                        if (!specialId.equals("")) {
                            mEtSpecialDes.setVisibility(View.VISIBLE);
                        } else {
                            mEtSpecialDes.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void dismiss() {
                        makeWindowLight();
                    }
                });
                departmentPop.show(mRlMain);
                makeWindowDark();
                break;
            case id.tv_add_person:
                Intent intent = new Intent(this, DispatchingActivity.class);
                intent.putExtra(DispatchingActivity.KEY_FROM, DispatchingActivity.FROM_PROCESS);
                startActivity(intent);
                break;
        }
    }

    private void uploadFile() {
        ArrayList<File> files = new ArrayList<>();
        if (!TextUtils.isEmpty(mAudioPath)) {
            files.add(new File(mAudioPath));
        }
        ArrayList<ImageItem> images = new ArrayList<>(mImgData);
        images.remove(images.size() - 1);
        for (ImageItem imageItem : images) {
            if (!imageItem.isVideo()) {
                Bitmap bitmap = BitCompressUtil.getSmallBitmap(imageItem.getPath());
                File file = new File(Constant.BXT_IMAGE_COMPRESS);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File imageFile = new File(file, String.valueOf(System.currentTimeMillis()) + ".jpg");
                BitCompressUtil.compressBmpToFile(bitmap, imageFile);
                files.add(imageFile);
            } else {
                files.add(new File(imageItem.getPath()));
            }
        }
        PostRequest<UpLoadFile> request = OkGo.<UpLoadFile>post(Api.get().getFile())
                .tag(this);
        for (int i = 0; i < files.size(); i++) {
            request.params("file_imgs" + i, files.get(i));
        }
        request
                .execute(new DialogCallback<UpLoadFile>(UpLoadFile.class, this) {
                    @Override
                    public void onStart(Request<UpLoadFile, ? extends Request> request) {
                        super.onStart(request);
                        showToast("正在上传文件");
                    }

                    @Override
                    public void onSuccess(Response<UpLoadFile> response) {
                        UpLoadFile loadFile = response.body();
                        String resCode = loadFile.getReturncode();
                        if (resCode.equals("0")) {
                            fileIds = loadFile.getFile_ids();
                            LogUtils.i(fileIds);
//                            showToast("上传完成");
                            submit();
                        } else {
                            showToast("上传文件失败");
                        }
                    }

                    @Override
                    public void onError(Response<UpLoadFile> response) {
                        super.onError(response);
                        showToast("上传文件错误：" + response.message());
                    }
                });
    }

    private String getFaultTypeJson() {
        Gson gson = new Gson();
        String s = gson.toJson(mFaultTypes);
        return s == null ? "" : s;
    }

    private void submit() {
        String cause = mEtCause.getText() == null ? "" : mEtCause.getText().toString();
        String specialNode = mEtSpecialDes.getText() == null ? "" : mEtSpecialDes.getText().toString();
//        if(TextUtils.isEmpty(cause)){
//            showToast("请填写备注");
//            return;
//        }
        String json = getFaultTypeJson();
        String fix = fixState == 1 ? "已修好" : "未修好";
        OkGo.<Finish>post(Api.get().getOrderPress())
                .tag(this)
                .params("id", orderId)
                .params("user_ids", "")
                .params("opt_uid", mUserId)
                .params("zhuangtai", fix)
                .params("gongzuomiaoshu", cause)
                .params("faulttype_info", json)
                .params("wc_file_ids", fileIds)
                .params("collection", specialId)
                .params("collection_note", specialNode)
                .params("jiedan_time", receiveTimeStamp)
                .params("end_time", finishTimeStamp)
                .params("continue_state", continueState)
                .params("user_ids", weixiuyuanIds)
                .execute(new DialogCallback<Finish>(Finish.class, this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish finish = response.body();
                        if (finish.getReturncode().equals("0")) {
                            showToast("提交完成");
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            showToast("提交失败：" + finish.getReturnmsg());
                        }
                    }
                });
    }

    //选择故障类型
    private void showFaultTypePop() {
        View view = LayoutInflater.from(this).inflate(layout.pop_select_place, null);
        TextView tv_cancel = view.findViewById(id.tv_cancel);
        TextView tv_confirm = view.findViewById(id.tv_confirm);
        RecyclerView rvLeft = view.findViewById(id.rl_place_1);
        LinearLayoutManager managerL = new LinearLayoutManager(this);
        managerL.setOrientation(LinearLayoutManager.VERTICAL);
        rvLeft.setLayoutManager(managerL);
        RecyclerView rvRight = view.findViewById(id.rl_place_2);
        LinearLayoutManager managerR = new LinearLayoutManager(this);
        managerR.setOrientation(LinearLayoutManager.VERTICAL);
        rvRight.setLayoutManager(managerR);
        final BaseQuickAdapter leftAdapter = new BaseQuickAdapter<FaultType.DataBean, BaseViewHolder>(layout.item_my_pop_list, mFaultTypeLeft) {
            @Override
            protected void convert(BaseViewHolder helper, FaultType.DataBean item) {
                helper.setText(id.tv_name, item.getGzlx_type());
                if (item.isClicked()) {
                    helper.setTextColor(id.tv_name, ContextCompat.getColor(getApplicationContext(), color.text_color));
                    helper.setBackgroundRes(id.rl_item, color.gray);
                } else {
                    helper.setTextColor(id.tv_name, ContextCompat.getColor(getApplicationContext(), color.black));
                    helper.setBackgroundRes(id.rl_item, color.white);
                }
            }
        };
        final BaseQuickAdapter rightAdapter = new BaseQuickAdapter<FaultType.DataBean.GzlxListsBean, BaseViewHolder>(layout.item_my_pop_list, mFaultTypeRight) {
            @Override
            protected void convert(BaseViewHolder helper, FaultType.DataBean.GzlxListsBean item) {
                helper.setText(id.tv_name, item.getGzlx_name());
                if (item.isClicked()) {
                    helper.setTextColor(id.tv_name, ContextCompat.getColor(getApplicationContext(), color.text_color));
                    helper.setBackgroundRes(id.rl_item, color.gray);
                } else {
                    helper.setTextColor(id.tv_name, ContextCompat.getColor(getApplicationContext(), color.black));
                    helper.setBackgroundRes(id.rl_item, color.white);
                }
            }
        };
        leftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<FaultType.DataBean> data = leftAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                mFaultTypeRight.clear();
                mFaultTypeRight.addAll(data.get(position).getGzlx_lists());
                faultNameRight = "";
                faultRightId = "";
                faultLeftId = data.get(position).getId();
                faultName = data.get(position).getGzlx_type();
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();
            }
        });
        rvLeft.setAdapter(leftAdapter);

        rightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<FaultType.DataBean.GzlxListsBean> data = rightAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                faultRightId = data.get(position).getGzlx_id();
                faultNameRight = data.get(position).getGzlx_name();
                rightAdapter.notifyDataSetChanged();
            }
        });
        rvRight.setAdapter(rightAdapter);

        setPop(view, 1);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFaultTypes.add(new FaultTypeSelect(faultRightId, faultLeftId,
                        faultNameRight.equals("") ? faultName : faultName + "-" + faultNameRight, String.valueOf(1)));
                mFaultTypeAdapter.notifyDataSetChanged();
                mPop.dismiss();
            }
        });
    }

    private void setPop(View view, int heightType) {
        mPop = new PopupWindow(view, 5 * mScreenWidth / 6, heightType == 1 ? 2 * mScreenWidth / 3 : ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        mPop.showAtLocation(mRlMain, Gravity.CENTER, 0, 0);
    }

    //否退回工单状态
    private void showBackStatePop() {
        View view = LayoutInflater.from(this).inflate(layout.pop_confirm_back_state, null);
        TextView tv_in_work = view.findViewById(id.tv_in_work);
        TextView tv_out_work = view.findViewById(id.tv_out_work);
        TextView tv_pop_title = view.findViewById(id.tv_pop_title);
        tv_pop_title.setText("是否回退工单？");
        ImageView tv_close = view.findViewById(id.tv_close);
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mRlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_in_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                continueState = "1";
                submitOrder();
                mPop.dismiss();
            }
        });
        tv_out_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                continueState = "2";
                submitOrder();
                mPop.dismiss();
            }
        });
    }

    @Override
    protected void setTime(String time) {
        try {
            if (isReceiveTime) {
                mTvReceiveTime.setText(time);
                receiveTimeStamp = GetTimeUtil.ymdhm2Timestamp2(time);

            } else {
                mTvFinishTime.setText(time);
                finishTimeStamp = GetTimeUtil.ymdhm2Timestamp2(time);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void initRecycleView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRlPic.setLayoutManager(manager);
        final Uri imageUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + mipmap.add_photo);
        mImgData.add(new ImageItem(imageUri, false, ""));
        mPicAdapter = new PicRecycleAdapter(layout.item_select_pic, mImgData);
        mRlPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == mImgData.size() - 1) {
                    showPicPop(mRlMain);
                    makeWindowDark();
                } else {
                    ArrayList<ImageItem> images = new ArrayList<>(mImgData);
                    images.remove(images.size() - 1);
                    Intent intent = new Intent(getApplicationContext(), ImagePreviewActivity.class);
                    intent.putExtra(CURRENT_POSITION, position);
                    intent.putExtra(IMAGE_DATA, images);
                    startActivity(intent);
                }
            }
        });

        LinearLayoutManager faultTypeManager = new LinearLayoutManager(this);
        mRvFaultType.setLayoutManager(faultTypeManager);
        mFaultTypeAdapter = new FaultTypeAdapter(layout.item_fault_type, mFaultTypes);
        mRvFaultType.setAdapter(mFaultTypeAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CreateConst.REQUEST_CODE_CHOOSE_PIC && resultCode == RESULT_OK) {
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    if (!mImgData.contains(uri)) {
                        mImgData.add(0, new ImageItem(uri, false, PathUtils.getPath(this, uri)));
                    }
                }
                mPicAdapter.notifyDataSetChanged();
            }
            LogUtils.i("OnActivityResult ", String.valueOf(Matisse.obtainOriginalState(data)));
        }
        if (requestCode == CreateConst.REQUEST_CODE_TAKE_PIC && resultCode == 101) {
            String path = data.getStringExtra("path");
            LogUtils.i("CJT", "picture" + path);
            Uri picUri = getImageUri(path);
            LogUtils.i("CJT", "pictureuri" + picUri);
            if (!mImgData.contains(picUri)) {
                mImgData.add(0, new ImageItem(picUri, false, path));
            }
            mPicAdapter.notifyDataSetChanged();
        }
        if (requestCode == CreateConst.REQUEST_CODE_TAKE_PIC && resultCode == 102) {
            String path = data.getStringExtra("path");
            String videoPath = data.getStringExtra("video_path");
            LogUtils.i("CJT", "video" + path);
            Uri imgUri = getImageUri(path);
            Uri videoUri = getImageUri(videoPath);
            if (!mImgData.contains(imgUri)) {
                mImgData.add(0, new ImageItem(videoUri, true, videoUri, videoPath));
            }
            mPicAdapter.notifyDataSetChanged();
        }

    }

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mScrollView.requestDisallowInterceptTouchEvent(true);
            boolean ret = false;
            float downY = 0;
            int action = event.getAction();
            switch (v.getId()) {
                case id.tv_mic:
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            if (hasPermission(getApplication(), Manifest.permission.RECORD_AUDIO)) {
                                startAnim(true);
                                mMediaUtils.record();
                                ret = true;
                            } else {
                                showToast("缺少录音权限,请查看手机设置");
                                return false;
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            stopAnim();
                            if (isCancel) {
                                isCancel = false;
                                mMediaUtils.stopRecordUnSave();
                                showToast("取消保存");
                            } else {
                                int duration = getDuration(mChronometer.getText().toString());
                                switch (duration) {
                                    case -1:
                                        break;
                                    case -2:
                                        mMediaUtils.stopRecordUnSave();
                                        showToast("时间太短");
                                        break;
                                    default:
                                        mMediaUtils.stopRecordSave();
                                        String path = mMediaUtils.getTargetFilePath();
                                        mAudioPath = path;
                                        mIvPlayAudio.setVisibility(View.VISIBLE);
//                                        showToast("文件保存至：" + path);
                                        break;
                                }
                            }
                            break;
                        case MotionEvent.ACTION_MOVE:
                            float currentY = event.getY();
                            if (downY - currentY > 10) {
                                moveAnim();
                                isCancel = true;
                            } else {
                                isCancel = false;
                                startAnim(false);
                            }
                            break;
                    }
                    break;
            }
            return ret;
        }
    };

    Chronometer.OnChronometerTickListener tickListener = new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            if (SystemClock.elapsedRealtime() - chronometer.getBase() > 60 * 1000) {
                stopAnim();
                mMediaUtils.stopRecordSave();
                showToast("录音超时");
                String path = mMediaUtils.getTargetFilePath();
                mAudioPath = path;
//                showToast("文件保存至：" + path);
            }
        }
    };

    private void startAnim(boolean isStart) {
        mAudioLayout.setVisibility(View.VISIBLE);
        mTvInfo.setText("上滑取消");
        mTvMic.setBackgroundResource(color.text_color);
//        mMicIcn.setBackground(null);
        mMicIcn.setBackground(getResources().getDrawable(mipmap.ic_mic_white_24dp));
        if (isStart) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mChronometer.setFormat("%S");
            mChronometer.start();
        }
    }

    private void stopAnim() {
        mAudioLayout.setVisibility(View.GONE);
        mTvMic.setBackgroundResource(color.blue_bg);
        mChronometer.stop();
    }

    private void moveAnim() {
        mTvInfo.setText("松手取消");
        mMicIcn.setBackground(null);
        mMicIcn.setBackground(getResources().getDrawable(mipmap.ic_undo_black_24dp));
    }
}
